#include "UsrAI.h"

#include "Human.h"
#include <QDebug>

// 定义全局变量
tagGame tagUsrGame;
ins UsrIns;


// 全局变量
bool houseBuilt = false;
int hunterSN = -1;
int woodcutter1SN = -1;
int woodcutter2SN = -1;
int animalHunterSN = -1;
int targetPopulation = 9;
int houseCount = 0;
int targetHouseCount = 7;
bool houseBuilding = false;
int houseBuilderSN = -1;  // 专门用于建造房屋的农民
int prevFarmerCount = 0;  // 上一帧村民数量，用于检测新产生的村民
int hunterSN2 = -1;
int hunterSN3 = -1;
int hunterSN4 = -1;

// 谷仓相关变量
bool granaryBuilt = false;
bool granaryBuilding = false;
int granaryBuilderSN = -1;

// 船坞相关变量
int dockBuilderSN = -1;
int dockExplorerSN = -1;

// 房屋寻址起点与市镇中心坐标（用于加速连续寻址）
int begin_x1 = -1;
int begin_y1 = -1;
int cx = -1;
int cy = -1;

void UsrAI::processData()
{
    tagInfo myInfo = getInfo();
    int currentPopulation = myInfo.farmers.size() + myInfo.armies.size();
    // 两座房屋完成后，任意空闲村民建造谷仓
    if (houseCount >= 2 && !granaryBuilt && !granaryBuilding) {
        if (granaryBuilderSN == -1) {
            // 寻找空闲村民建造谷仓
            for (const auto& farmer : myInfo.farmers) {
                if (farmer.NowState == HUMAN_STATE_IDLE &&
                    farmer.SN != houseBuilderSN
                    ) {
                    granaryBuilderSN = farmer.SN;
                    break;
                }
            }
        }
    }
    

    

    prevFarmerCount = static_cast<int>(myInfo.farmers.size());
    
    // 检查房屋状态
    checkHouseStatus(myInfo);
    

    
    // 检查谷仓状态
    checkGranaryStatus(myInfo);
    
    // 房屋建造逻辑：只建两座房屋
    bool allowHouseBuildNow = (houseCount < 2);
    if (allowHouseBuildNow && !houseBuilding) {
        if (houseBuilderSN == -1) {
            // 找一个空闲农民来建造房屋
            for (const auto& farmer : myInfo.farmers) {
                if (farmer.NowState == HUMAN_STATE_IDLE && farmer.SN != hunterSN && 
                    farmer.SN != woodcutter1SN && farmer.SN != woodcutter2SN
                    ) {
                    houseBuilderSN = farmer.SN;
                    break;
                }
            }
        }
        
        if (houseBuilderSN != -1 && !houseBuilding) {
            for (const auto& f : myInfo.farmers) {
                if (f.SN == houseBuilderSN && f.NowState == HUMAN_STATE_IDLE) {
                    // 以自身为圆心，通过环形扩张找到最近 2x2 空地
                    int bx = -1, by = -1;
                    for (const auto& ff : myInfo.farmers) if (ff.SN == houseBuilderSN) { bx = ff.BlockDR; by = ff.BlockUR; break; }
                    std::pair<int,int> buildPos = {-1, -1};
                    if (bx != -1) {
                        int fx=-1, fy=-1;
                        if (findEmpty2x2(myInfo, bx, by, fx, fy)) buildPos = {fx, fy};
                    }
                    if (buildPos.first != -1 && buildPos.second != -1) {
                        // 再次详细检查位置是否适合
                        bool isSuitable = isAreaSuitableForBuilding(buildPos.first, buildPos.second, myInfo);
                        if (isSuitable) {
                            // 检查建造者是否能到达该位置
                            if (canBuilderReachPosition(houseBuilderSN, buildPos.first, buildPos.second, myInfo)) {
                                // 若建造者占在2x2脚印内，先挪到相邻可站立平地草地
                                if (!relocateBuilderOutOfFootprint(houseBuilderSN, buildPos.first, buildPos.second, myInfo)) {
                                    break;
                                }
                                // 最后一次安全检查，确保位置仍然可用
                                if (isAreaSuitableForBuilding(buildPos.first, buildPos.second, myInfo)) {
                                    int result = HumanBuild(houseBuilderSN, BUILDING_HOME, buildPos.first, buildPos.second);
                                    if (result > 0) {
                                        houseBuilding = true;
                                        // 记录建房者连建计数（预登记）
                                        // 注意：最终以houseCount为准，此计数仅用于流程控制
                                        // 可在需要时加入更严格的完成检测逻辑
                                        // houseBuilderBuiltHomes++;
                                        // 更新下一次小范围搜索的起点，沿着x方向推进；越界则换行到y+2并从cx开始
                                        int home_x = buildPos.first;
                                        int home_y = buildPos.second;
                                        // 初始化中心点（若未初始化）
                                        if (cx == -1 || cy == -1) {
                                            // 在上方函数中已查找过中心点，这里保守处理一次
                                            for (const auto& b : myInfo.buildings) {
                                                if (b.Type == BUILDING_CENTER) { cx = b.BlockDR; cy = b.BlockUR; break; }
                                            }
                                        }
                                        if (begin_x1 == -1 || begin_y1 == -1) { begin_x1 = cx; begin_y1 = cy; }
                                        if (home_x + 2 >= MAP_L - 1) {
                                            begin_x1 = cx;
                                            begin_y1 = std::min(home_y + 2, MAP_U - 2);
                                        } else {
                                            begin_x1 = home_x + 2;
                                            begin_y1 = home_y;
                                        }
                                    }
                                }
                            }
                        } else {
                            if (!moveBuilderToExplore(houseBuilderSN, myInfo)) {
                                // 移动探索失败，稍后重试
                            }
                        }
                    }
                    break;
                }
            }
        }
    }
    
    // 新产生的村民分配逻辑
    if ((int)myInfo.farmers.size() > prevFarmerCount) {
        // 有新村民产生
        int newFarmerSN = myInfo.farmers.back().SN; // 最新产生的村民
    }

    // 谷仓建造逻辑（第五人建造，不依赖房屋数量）
    if (granaryBuilderSN != -1 && !granaryBuilt && myInfo.Wood >= 150) {
        buildGranary(myInfo);
    }
    
    // 时代升级逻辑
    if (granaryBuilt && myInfo.Meat >= 500 && myInfo.civilizationStage == CIVILIZATION_STONEAGE) {
        upgradeToToolAge(myInfo);
    }
    
    // 村民生产逻辑：时代升级前9人，升级后15人
    int currentTargetPopulation = (myInfo.civilizationStage > CIVILIZATION_STONEAGE) ? 15 : targetPopulation;
    if (currentPopulation < currentTargetPopulation) {
        produceVillagers(myInfo);
    }
    
    // 基本农民工作分配（开局就开始分配，但排除建造者）
    assignFarmerWork(myInfo);
}

    // 检查房屋状态
    void UsrAI::checkHouseStatus(const tagInfo& myInfo)
    {
        // 统计当前房屋数量
        int currentHouseCount = 0;
        for (const auto& building : myInfo.buildings) {
            if (building.Type == BUILDING_HOME) {
                currentHouseCount++;
            }
        }
        
        // 如果房屋数量增加，更新状态
        if (currentHouseCount > houseCount) {
            houseCount = currentHouseCount;
            houseBuilding = false;
            // 房屋建造完成后，建完两座就释放建造者
            if (currentHouseCount >= 2) {
                houseBuilderSN = -1; // 释放建造者
            }
        }
    }

// 寻找适合建造房屋的位置（2x2陆地空地）
std::pair<int, int> UsrAI::findSuitableBuildPosition(const tagInfo& myInfo)
{
    // 1) 获取市镇中心坐标
    int centerX = -1, centerY = -1;
    for (const auto& building : myInfo.buildings) {
        if (building.Type == BUILDING_CENTER) { centerX = building.BlockDR; centerY = building.BlockUR; break; }
    }
    if (centerX == -1 || centerY == -1) { return {-1, -1}; }
    cx = centerX; cy = centerY;

    // 初始化小范围搜索起点：避开市镇中心3x3占地（向外偏移2格）
    if (begin_x1 == -1 || begin_y1 == -1) {
        begin_x1 = std::min(std::max(0, cx + 2), MAP_L - 2);
        begin_y1 = std::min(std::max(0, cy), MAP_U - 2);
    }



    // 计算市镇中心3x3占地区域
    int tcMinX = std::max(0, cx - 1);
    int tcMaxX = std::min(MAP_L - 1, cx + 1);
    int tcMinY = std::max(0, cy - 1);
    int tcMaxY = std::min(MAP_U - 1, cy + 1);
    auto intersectsTownCenter = [&](int x, int y) -> bool {
        // 2x2: [x..x+1], [y..y+1] 与 3x3: [tcMinX..tcMaxX], [tcMinY..tcMaxY] 是否相交
        int x1 = x, x2 = x + 1, y1 = y, y2 = y + 1;
        bool noOverlap = (x2 < tcMinX) || (x1 > tcMaxX) || (y2 < tcMinY) || (y1 > tcMaxY);
        return !noOverlap;
    };

    // 2) 小范围优先搜索：从起点开始的5x5窗口
    for (int i = std::max(0, begin_x1); i <= std::min(MAP_L - 2, begin_x1 + 7); ++i) {
        for (int j = std::max(0, begin_y1); j <= std::min(MAP_U - 2, begin_y1 + 7); ++j) {
            if (intersectsTownCenter(i, j)) continue; // 跳过市镇中心覆盖范围
            if (isAreaSuitableForBuilding(i, j, myInfo)) {
                return {i, j};
            }
        }
    }

    // 3) 螺旋搜索：以市镇中心为中心，按半径扩展
    const int dx[4] = {1, 0, -1, 0};
    const int dy[4] = {0, 1, 0, -1};
    const int max_R = 50;
    for (int radius = 3; radius <= max_R; ++radius) {
        int current_x = cx, current_y = cy;
        for (int dir = 0; dir < 4; ++dir) {
            for (int step = 0; step < radius * 2; ++step) {
                current_x += dx[dir];
                current_y += dy[dir];
                if (current_x < 0 || current_y < 0 || current_x >= MAP_L - 1 || current_y >= MAP_U - 1) continue;
                if (!intersectsTownCenter(current_x, current_y) &&
                    isAreaSuitableForBuilding(current_x, current_y, myInfo)) {
                    return {current_x, current_y};
                }
            }
        }
    }

    // 4) 全图兜底搜索
    for (int i = 0; i < MAP_L - 1; ++i) {
        for (int j = 0; j < MAP_U - 1; ++j) {
            if (!intersectsTownCenter(i, j) &&
                isAreaSuitableForBuilding(i, j, myInfo)) {
                return {i, j};
            }
        }
    }

    return {-1, -1};
}

// 以建造者自身为中心寻找2x2空地（多圈半径递增，优先近距离）
std::pair<int, int> UsrAI::findBuildPosAroundBuilder(const tagInfo& myInfo, int builderSN)
{
    int bx = -1, by = -1;
    for (const auto& f : myInfo.farmers) {
        if (f.SN == builderSN) { bx = f.BlockDR; by = f.BlockUR; break; }
    }
    if (bx == -1) return {-1, -1};

    // 半径从1到40，先检查四向与对角，再检查整圈边界
    const int maxR = 40;
    for (int r = 1; r <= maxR; ++r) {
        // 四向与对角优先
        int dirs[8][2] = {{0,r},{r,0},{0,-r},{-r,0},{r,r},{r,-r},{-r,r},{-r,-r}};
        for (auto& d : dirs) {
            int x = bx + d[0], y = by + d[1];
            if (x < 0 || y < 0 || x >= MAP_L - 1 || y >= MAP_U - 1) continue;
            if (isAreaSuitableForBuilding(x, y, myInfo)) return {x, y};
        }
        // 圈边扫描
        for (int dx = -r; dx <= r; ++dx) {
            for (int dy = -r; dy <= r; ++dy) {
                if (abs(dx) != r && abs(dy) != r) continue; // 只取边界
                int x = bx + dx, y = by + dy;
                if (x < 0 || y < 0 || x >= MAP_L - 1 || y >= MAP_U - 1) continue;
                if (isAreaSuitableForBuilding(x, y, myInfo)) return {x, y};
            }
        }
    }
    return {-1, -1};
}

// 判断 (x,y) 及其右上 3 格是否都是可建造平地且未被占用
bool UsrAI::is2x2Empty(const tagInfo& info, int x, int y) const
{
    if (x < 0 || y < 0 || x + 1 >= MAP_L || y + 1 >= MAP_U) return false;
    if (info.theMap == nullptr) return false;

    // 高度必须一致且为草地平地
    int baseH = (*info.theMap)[x][y].height;
    for (int dx = 0; dx <= 1; ++dx) {
        for (int dy = 0; dy <= 1; ++dy) {
            const auto& cell = (*info.theMap)[x + dx][y + dy];
            if (cell.type != MAPPATTERN_GRASS || cell.height != baseH || baseH != MAPHEIGHT_FLAT) return false;
        }
    }

    // 占用检测
    auto conflict = [&](int bx, int by) -> bool {
        for (const auto& b : info.buildings) {
            // 保守估算建筑占地 3x2（根据已有数据习惯）
            if (bx >= b.BlockDR && bx < b.BlockDR + 3 &&
                by >= b.BlockUR && by < b.BlockUR + 2) return true;
        }
        for (const auto& r : info.resources) if (r.BlockDR == bx && r.BlockUR == by) return true;
        for (const auto& f : info.farmers)   if (f.BlockDR == bx && f.BlockUR == by) return true;
        for (const auto& a : info.armies)    if (a.BlockDR == bx && a.BlockUR == by) return true;
        for (const auto& f : info.enemy_farmers) if (f.BlockDR == bx && f.BlockUR == by) return true;
        for (const auto& a : info.enemy_armies)  if (a.BlockDR == bx && a.BlockUR == by) return true;
        return false;
    };

    for (int dx = 0; dx <= 1; ++dx) {
        for (int dy = 0; dy <= 1; ++dy) {
            if (conflict(x + dx, y + dy)) return false;
        }
    }
    return true;
}

// 以 (startX,startY) 为中心做环形扩张搜索可建的 2x2 空地
bool UsrAI::findEmpty2x2(const tagInfo& info, int startX, int startY, int& foundX, int& foundY)
{
    if (startX != m_lastCenterX || startY != m_lastCenterY) {
        m_searchRadius = 0;
        m_lastCenterX = startX;
        m_lastCenterY = startY;
    }

    const int maxR = 50;
    for (; m_searchRadius <= maxR; ++m_searchRadius) {
        int r = m_searchRadius;
        if (r == 0) {
            if (is2x2Empty(info, startX, startY)) { foundX = startX; foundY = startY; return true; }
            continue;
        }
        // 四向与对角优先
        int dirs[8][2] = {{0,r},{r,0},{0,-r},{-r,0},{r,r},{r,-r},{-r,r},{-r,-r}};
        for (auto& d : dirs) {
            int x = startX + d[0], y = startY + d[1];
            if (x < 0 || y < 0 || x >= MAP_L - 1 || y >= MAP_U - 1) continue;
            if (is2x2Empty(info, x, y)) { foundX = x; foundY = y; return true; }
        }
        // 环边扫描
        for (int dx = -r; dx <= r; ++dx) {
            for (int dy = -r; dy <= r; ++dy) {
                if (abs(dx) != r && abs(dy) != r) continue;
                int x = startX + dx, y = startY + dy;
                if (x < 0 || y < 0 || x >= MAP_L - 1 || y >= MAP_U - 1) continue;
                if (is2x2Empty(info, x, y)) { foundX = x; foundY = y; return true; }
            }
        }
    }
    return false;
}
// 若以自身为圆心找不到空地，则让建造者移动到附近未占用的平地草地，帮助跳出阻塞区域
bool UsrAI::moveBuilderToExplore(int builderSN, const tagInfo& myInfo)
{
    // 找到建造者
    const tagFarmer* builder = nullptr;
    for (const auto& f : myInfo.farmers) if (f.SN == builderSN) { builder = &f; break; }
    if (!builder) return false;

    // 在以自身为中心的曼哈顿环上挑一个最近的可站位置
    for (int r = 2; r <= 6; ++r) {
        for (int dx = -r; dx <= r; ++dx) {
            int dy1 = r - abs(dx);
            int dy2 = -dy1;
            int cand[2][2] = {{builder->BlockDR + dx, builder->BlockUR + dy1}, {builder->BlockDR + dx, builder->BlockUR + dy2}};
            for (auto& p : cand) {
                int x = p[0], y = p[1];
                if (x < 0 || y < 0 || x >= MAP_L || y >= MAP_U) continue;
                if (isSingleTileFreeFlatGrass(x, y, myInfo)) {
                    double moveDR = x * BLOCKSIDELENGTH + BLOCKSIDELENGTH / 2.0;
                    double moveUR = y * BLOCKSIDELENGTH + BLOCKSIDELENGTH / 2.0;
                    HumanMove(builderSN, moveDR, moveUR);
                    return true;
                }
            }
        }
    }
    return false;
}

// 检查区域是否适合建造房屋（2x2陆地空地）
bool UsrAI::isAreaSuitableForBuilding(int x, int y, const tagInfo& myInfo)
{
    if (myInfo.theMap == nullptr) {
        return false;
    }
    
    // 检查2x2区域是否适合建造房屋
    for (int dx = 0; dx < 2; dx++) {
        for (int dy = 0; dy < 2; dy++) {
            int checkX = x + dx;
            int checkY = y + dy;
            
            // 检查地图边界
            if (checkX >= MAP_L || checkY >= MAP_U) {
                return false;
            }
            
            // 检查地形高度与样式（必须是平地且为草地）
            int currentHeight = (*myInfo.theMap)[checkX][checkY].height;
            int currentPattern = (*myInfo.theMap)[checkX][checkY].type;
            if (currentHeight != MAPHEIGHT_FLAT) {
                return false;
            }
            if (currentPattern != MAPPATTERN_GRASS) {
                return false;
            }
            
            // 检查是否有其他建筑占用
            for (const auto& building : myInfo.buildings) {
                if (building.BlockDR == checkX && building.BlockUR == checkY) {
                    return false;
                }
            }
            
            // 检查是否有资源占用
            for (const auto& resource : myInfo.resources) {
                if (resource.BlockDR == checkX && resource.BlockUR == checkY) {
                    return false;
                }
            }
            
            // 检查是否有农民占用
            for (const auto& farmer : myInfo.farmers) {
                if (farmer.BlockDR == checkX && farmer.BlockUR == checkY) {
                    return false;
                }
            }
            
            // 检查是否有军队占用
            for (const auto& army : myInfo.armies) {
                if (army.BlockDR == checkX && army.BlockUR == checkY) {
                    return false;
                }
            }
            
            // 检查是否有敌方单位占用
            for (const auto& enemy_farmer : myInfo.enemy_farmers) {
                if (enemy_farmer.BlockDR == checkX && enemy_farmer.BlockUR == checkY) {
                    return false;
                }
            }
            
            for (const auto& enemy_army : myInfo.enemy_armies) {
                if (enemy_army.BlockDR == checkX && enemy_army.BlockUR == checkY) {
                    return false;
                }
            }
        }
    }
    
    return true;
}

// 村民生产逻辑：人口达到12人后停止
void UsrAI::produceVillagers(const tagInfo& myInfo)
{
    // 找到市镇中心
    int centerSN = -1;
    for (const auto& building : myInfo.buildings) {
        if (building.Type == BUILDING_CENTER) {
            centerSN = building.SN;
            break;
        }
    }
    
    if (centerSN == -1) {
        return;
    }

    
    // 检查市镇中心是否正在生产
    bool isProducing = false;
    for (const auto& building : myInfo.buildings) {
        if (building.SN == centerSN && building.Project != 0) {
            isProducing = true;
            break;
        }
    }
    
    // 如果没有在生产且食物充足，开始生产村民
    if (!isProducing && myInfo.Meat >= 50) {
        BuildingAction(centerSN, BUILDING_CENTER_CREATEFARMER);
    }
}

// 农民工作分配：优先补足4人狩猎队，然后安排砍树
void UsrAI::assignFarmerWork(const tagInfo& myInfo)
{
    // 优先分配猎人（最多4人）
    assignHunter(myInfo);
    
    // 额外猎人（基于空闲村民补足到4）
    if (hunterSN2 == -1 || !isFarmerAlive(hunterSN2, myInfo)) hunterSN2 = -1;
    if (hunterSN3 == -1 || !isFarmerAlive(hunterSN3, myInfo)) hunterSN3 = -1;
    if (hunterSN4 == -1 || !isFarmerAlive(hunterSN4, myInfo)) hunterSN4 = -1;
    
    auto assignExtraHunter = [&](int& slot){
        if (slot != -1) return;
        for (const auto& farmer : myInfo.farmers) {
            if (farmer.NowState == HUMAN_STATE_IDLE &&
                farmer.SN != houseBuilderSN &&
                farmer.SN != granaryBuilderSN &&
                farmer.SN != hunterSN && farmer.SN != woodcutter1SN && farmer.SN != woodcutter2SN &&
                farmer.SN != hunterSN2 && farmer.SN != hunterSN3 && farmer.SN != hunterSN4) {
                slot = farmer.SN; 
                break;
            }
        }
    };
    assignExtraHunter(hunterSN2);
    assignExtraHunter(hunterSN3);
    assignExtraHunter(hunterSN4);
    
    // 狩猎队满员后，分配伐木工
    int hunterCount = (hunterSN != -1 ? 1 : 0) + (hunterSN2 != -1 ? 1 : 0) + 
                     (hunterSN3 != -1 ? 1 : 0) + (hunterSN4 != -1 ? 1 : 0);
    if (hunterCount >= 4) {
        assignWoodcutter1(myInfo);
        assignWoodcutter2(myInfo);
        assignAnimalHunter(myInfo);
    } else {
        // 如果狩猎队未满员，也要分配伐木工，避免村民闲置
        assignWoodcutter1(myInfo);
        assignWoodcutter2(myInfo);
        assignAnimalHunter(myInfo);
    }
    
    // 确保分配的工作持续进行
    ensureHunterWorking(myInfo);
    if (hunterSN2 != -1) ensureHunterWorking(myInfo);
    if (hunterSN3 != -1) ensureHunterWorking(myInfo);
    if (hunterSN4 != -1) ensureHunterWorking(myInfo);
    ensureWoodcutterWorking(myInfo, woodcutter1SN);
    ensureWoodcutterWorking(myInfo, woodcutter2SN);
    ensureAnimalHunterWorking(myInfo);
    

}

// 分配猎人
void UsrAI::assignHunter(const tagInfo& myInfo)
{
    if (hunterSN == -1) {
        for (const auto& farmer : myInfo.farmers) {
            if (farmer.NowState == HUMAN_STATE_IDLE &&
                farmer.SN != dockBuilderSN &&
                farmer.SN != houseBuilderSN &&
                farmer.SN != granaryBuilderSN &&
                farmer.SN != dockExplorerSN) {
                hunterSN = farmer.SN;
                break;
            }
        }
    }
}

// 分配伐木工1
void UsrAI::assignWoodcutter1(const tagInfo& myInfo)
{
    if (woodcutter1SN == -1) {
        for (const auto& farmer : myInfo.farmers) {
            if (farmer.NowState == HUMAN_STATE_IDLE &&
                farmer.SN != dockBuilderSN &&
                farmer.SN != houseBuilderSN &&
                farmer.SN != granaryBuilderSN &&
                farmer.SN != dockExplorerSN &&
                farmer.SN != hunterSN) {
                woodcutter1SN = farmer.SN;
                break;
            }
        }
    }
}

// 分配伐木工2
void UsrAI::assignWoodcutter2(const tagInfo& myInfo)
{
    if (woodcutter2SN == -1) {
        for (const auto& farmer : myInfo.farmers) {
            if (farmer.NowState == HUMAN_STATE_IDLE &&
                farmer.SN != dockBuilderSN &&
                farmer.SN != houseBuilderSN &&
                farmer.SN != granaryBuilderSN &&
                farmer.SN != dockExplorerSN &&
                farmer.SN != hunterSN &&
                farmer.SN != woodcutter1SN) {
                woodcutter2SN = farmer.SN;
                break;
            }
        }
    }
}

// 分配动物猎人
void UsrAI::assignAnimalHunter(const tagInfo& myInfo)
{
    if (animalHunterSN == -1) {
        for (const auto& farmer : myInfo.farmers) {
            if (farmer.NowState == HUMAN_STATE_IDLE &&
                farmer.SN != dockBuilderSN &&
                farmer.SN != houseBuilderSN &&
                farmer.SN != granaryBuilderSN &&
                farmer.SN != dockExplorerSN &&
                farmer.SN != hunterSN &&
                farmer.SN != woodcutter1SN &&
                farmer.SN != woodcutter2SN) {
                animalHunterSN = farmer.SN;
                break;
            }
        }
    }
}

// 确保猎人工作
void UsrAI::ensureHunterWorking(const tagInfo& myInfo)
{
    if (hunterSN != -1) {
        for (const auto& farmer : myInfo.farmers) {
            if (farmer.SN == hunterSN && farmer.NowState == HUMAN_STATE_IDLE) {
                // 寻找离猎人最近的羚羊
                auto animalResource = findNearestAnimalToFarmerSN(myInfo, hunterSN);
                if (animalResource != -1) {
                    HumanAction(hunterSN, animalResource);
                }
                break;
            }
        }
    }
}

// 确保伐木工工作
void UsrAI::ensureWoodcutterWorking(const tagInfo& myInfo, int woodcutterSN)
{
    if (woodcutterSN != -1) {
        for (const auto& farmer : myInfo.farmers) {
            if (farmer.SN == woodcutterSN && farmer.NowState == HUMAN_STATE_IDLE) {
                // 寻找离伐木工最近的树木
                auto treeResource = findNearestTreeToFarmerSN(myInfo, woodcutterSN);
                if (treeResource != -1) {
                    HumanAction(woodcutterSN, treeResource);
                }
                break;
            }
        }
    }
}

// 确保动物猎人工作
void UsrAI::ensureAnimalHunterWorking(const tagInfo& myInfo)
{
    if (animalHunterSN != -1) {
        for (const auto& farmer : myInfo.farmers) {
            if (farmer.SN == animalHunterSN && farmer.NowState == HUMAN_STATE_IDLE) {
                // 寻找离动物猎人最近的羚羊
                auto animalResource = findNearestAnimalToFarmerSN(myInfo, animalHunterSN);
                if (animalResource != -1) {
                    HumanAction(animalHunterSN, animalResource);
                }
                break;
            }
        }
    }
}

// 寻找最近的资源
std::pair<int, int> UsrAI::findNearestResource(const tagInfo& myInfo, int resourceType)
{
    if (myInfo.resources.empty()) return {-1, -1};
    
    // 找到市镇中心位置作为参考点
    int centerX = -1, centerY = -1;
    for (const auto& building : myInfo.buildings) {
        if (building.Type == BUILDING_CENTER) {
            centerX = building.BlockDR;
            centerY = building.BlockUR;
            break;
        }
    }
    
    if (centerX == -1 || centerY == -1) {
        // 如果没有市镇中心，返回第一个匹配的资源
        for (const auto& resource : myInfo.resources) {
            if (resource.Type == resourceType) {
                return {resource.BlockDR, resource.BlockUR};
            }
        }
        return {-1, -1};
    }
    
    // 寻找最近的指定类型资源
    int nearestDistance = INT_MAX;
    std::pair<int, int> nearestPos = {-1, -1};
    
    for (const auto& resource : myInfo.resources) {
        if (resource.Type == resourceType) {
            int distance = abs(resource.BlockDR - centerX) + abs(resource.BlockUR - centerY);
            if (distance < nearestDistance) {
                nearestDistance = distance;
                nearestPos = {resource.BlockDR, resource.BlockUR};
            }
        }
    }
    

    
    return nearestPos;
}

// 寻找最近的动物资源
std::pair<int, int> UsrAI::findNearestAnimalResource(const tagInfo& myInfo)
{
    if (myInfo.resources.empty()) return {-1, -1};
    
    // 找到市镇中心位置作为参考点
    int centerX = -1, centerY = -1;
    for (const auto& building : myInfo.buildings) {
        if (building.Type == BUILDING_CENTER) {
            centerX = building.BlockDR;
            centerY = building.BlockUR;
            break;
        }
    }
    
    if (centerX == -1 || centerY == -1) {
        // 如果没有市镇中心，返回第一个羚羊
        for (const auto& resource : myInfo.resources) {
            if (resource.Type == RESOURCE_GAZELLE) {
                return {resource.BlockDR, resource.BlockUR};
            }
        }
        return {-1, -1};
    }
    
    // 寻找最近的羚羊
    int nearestDistance = INT_MAX;
    std::pair<int, int> nearestPos = {-1, -1};
    
    for (const auto& resource : myInfo.resources) {
        if (resource.Type == RESOURCE_GAZELLE) {
            int distance = abs(resource.BlockDR - centerX) + abs(resource.BlockUR - centerY);
            if (distance < nearestDistance) {
                nearestDistance = distance;
                nearestPos = {resource.BlockDR, resource.BlockUR};
            }
        }
    }
    

    
    return nearestPos;
}

// 寻找最近的鱼资源
std::pair<int, int> UsrAI::findNearestFishResource(const tagInfo& myInfo)
{
    if (myInfo.resources.empty()) return {-1, -1};
    
    // 找到船坞位置作为参考点
    int dockX = -1, dockY = -1;
    for (const auto& building : myInfo.buildings) {
        if (building.Type == BUILDING_DOCK) {
            dockX = building.BlockDR;
            dockY = building.BlockUR;
            break;
        }
    }
    
    if (dockX == -1 || dockY == -1) {
        // 如果没有船坞，返回第一个鱼资源
        for (const auto& resource : myInfo.resources) {
            if (resource.Type == RESOURCE_FISH) {
                return {resource.BlockDR, resource.BlockUR};
            }
        }
        return {-1, -1};
    }
    
    // 寻找最近的鱼资源
    int nearestDistance = INT_MAX;
    std::pair<int, int> nearestPos = {-1, -1};
    
    for (const auto& resource : myInfo.resources) {
        if (resource.Type == RESOURCE_FISH) {
            int distance = abs(resource.BlockDR - dockX) + abs(resource.BlockUR - dockY);
            if (distance < nearestDistance) {
                nearestDistance = distance;
                nearestPos = {resource.BlockDR, resource.BlockUR};
            }
        }
    }
    

    
    return nearestPos;
}

// 寻找最近的鱼资源SN（用于HumanAction）
int UsrAI::findNearestFishResourceSN(const tagInfo& myInfo)
{
    if (myInfo.resources.empty()) return -1;
    
    // 找到船坞位置作为参考点
    int dockX = -1, dockY = -1;
    for (const auto& building : myInfo.buildings) {
        if (building.Type == BUILDING_DOCK) {
            dockX = building.BlockDR;
            dockY = building.BlockUR;
            break;
        }
    }
    
    if (dockX == -1 || dockY == -1) {
        // 如果没有船坞，返回第一个鱼资源
        for (const auto& resource : myInfo.resources) {
            if (resource.Type == RESOURCE_FISH) {
                return resource.SN;
            }
        }
        return -1;
    }
    
    // 寻找最近的鱼资源
    int nearestDistance = INT_MAX;
    int nearestSN = -1;
    
    for (const auto& resource : myInfo.resources) {
        if (resource.Type == RESOURCE_FISH) {
            int distance = abs(resource.BlockDR - dockX) + abs(resource.BlockUR - dockY);
            if (distance < nearestDistance) {
                nearestDistance = distance;
                nearestSN = resource.SN;
            }
        }
    }
    

    
    return nearestSN;
}

// 寻找离指定农民最近的树木
std::pair<int, int> UsrAI::findNearestTreeToFarmer(const tagInfo& myInfo, int farmerSN)
{
    if (myInfo.resources.empty()) return {-1, -1};
    
    // 找到指定农民的位置
    int farmerX = -1, farmerY = -1;
    for (const auto& farmer : myInfo.farmers) {
        if (farmer.SN == farmerSN) {
            farmerX = farmer.BlockDR;
            farmerY = farmer.BlockUR;
            break;
        }
    }
    
    if (farmerX == -1 || farmerY == -1) {

        return {-1, -1};
    }
    
    // 寻找离农民最近的树木
    int nearestDistance = INT_MAX;
    std::pair<int, int> nearestPos = {-1, -1};
    
    for (const auto& resource : myInfo.resources) {
        if (resource.Type == RESOURCE_TREE) {
            int distance = abs(resource.BlockDR - farmerX) + abs(resource.BlockUR - farmerY);
            if (distance < nearestDistance) {
                nearestDistance = distance;
                nearestPos = {resource.BlockDR, resource.BlockUR};
            }
        }
    }
    
    return nearestPos;
}

// 寻找离指定农民最近的树木SN（用于HumanAction）
int UsrAI::findNearestTreeToFarmerSN(const tagInfo& myInfo, int farmerSN)
{
    if (myInfo.resources.empty()) return -1;
    
    // 找到指定农民的位置
    int farmerX = -1, farmerY = -1;
    for (const auto& farmer : myInfo.farmers) {
        if (farmer.SN == farmerSN) {
            farmerX = farmer.BlockDR;
            farmerY = farmer.BlockUR;
            break;
        }
    }
    
    if (farmerX == -1 || farmerY == -1) {
        return -1;
    }
    
    // 寻找离农民最近的树木
    int nearestDistance = INT_MAX;
    int nearestSN = -1;
    
    for (const auto& resource : myInfo.resources) {
        if (resource.Type == RESOURCE_TREE) {
            int distance = abs(resource.BlockDR - farmerX) + abs(resource.BlockUR - farmerY);
            if (distance < nearestDistance) {
                nearestDistance = distance;
                nearestSN = resource.SN;
            }
        }
    }
    
    return nearestSN;
}

// 寻找离指定农民最近的羚羊
std::pair<int, int> UsrAI::findNearestAnimalToFarmer(const tagInfo& myInfo, int farmerSN)
{
    if (myInfo.resources.empty()) return {-1, -1};
    
    // 找到指定农民的位置
    int farmerX = -1, farmerY = -1;
    for (const auto& farmer : myInfo.farmers) {
        if (farmer.SN == farmerSN) {
            farmerX = farmer.BlockDR;
            farmerY = farmer.BlockUR;
            break;
        }
    }
    
    if (farmerX == -1 || farmerY == -1) {
        return {-1, -1};
    }
    
    // 寻找离农民最近的羚羊
    int nearestDistance = INT_MAX;
    std::pair<int, int> nearestPos = {-1, -1};
    
    for (const auto& resource : myInfo.resources) {
        if (resource.Type == RESOURCE_GAZELLE) {
            int distance = abs(resource.BlockDR - farmerX) + abs(resource.BlockUR - farmerY);
            if (distance < nearestDistance) {
                nearestDistance = distance;
                nearestPos = {resource.BlockDR, resource.BlockUR};
            }
        }
    }
    
    return nearestPos;
}

// 寻找离指定农民最近的羚羊SN（用于HumanAction）
int UsrAI::findNearestAnimalToFarmerSN(const tagInfo& myInfo, int farmerSN)
{
    if (myInfo.resources.empty()) return -1;
    
    // 找到指定农民的位置
    int farmerX = -1, farmerY = -1;
    for (const auto& farmer : myInfo.farmers) {
        if (farmer.SN == farmerSN) {
            farmerX = farmer.BlockDR;
            farmerY = farmer.BlockUR;
            break;
        }
    }
    
    if (farmerX == -1 || farmerY == -1) {
        return -1;
    }
    
    // 寻找离农民最近的羚羊
    int nearestDistance = INT_MAX;
    int nearestSN = -1;
    
    for (const auto& resource : myInfo.resources) {
        if (resource.Type == RESOURCE_GAZELLE) {
            int distance = abs(resource.BlockDR - farmerX) + abs(resource.BlockUR - farmerY);
            if (distance < nearestDistance) {
                nearestDistance = distance;
                nearestSN = resource.SN;
            }
        }
    }
    
    return nearestSN;
}

// 处理军队（简化版本）
void UsrAI::handleArmy(const tagInfo& myInfo)
{
    // 暂时不处理军队
}

// 检查农民是否存活
bool UsrAI::isFarmerAlive(int farmerSN, const tagInfo& myInfo)
{
    for (const auto& farmer : myInfo.farmers) {
        if (farmer.SN == farmerSN) {
            return true;
        }
    }
    return false;
}

// 获取游戏信息
tagInfo UsrAI::getInfo()
{
    return tagUsrGame.getInfo();
}

// 添加指令
int UsrAI::AddToIns(instruction ins)
{
    UsrIns.lock.lock();
    ins.id = UsrIns.g_id;
    UsrIns.g_id++;
    UsrIns.instructions.push(ins);
    UsrIns.lock.unlock();
    return ins.id;
}

// 清空指令返回
void UsrAI::clearInsRet()
{
    tagUsrGame.clearInsRet();
}



// 检查谷仓状态
void UsrAI::checkGranaryStatus(const tagInfo& myInfo)
{
    // 统计当前谷仓数量
    int currentGranaryCount = 0;
    for (const auto& building : myInfo.buildings) {
        if (building.Type == BUILDING_GRANARY) {
            currentGranaryCount++;
        }
    }
    
    // 如果谷仓数量增加，更新状态
    if (currentGranaryCount > 0 && !granaryBuilt) {
        granaryBuilt = true;
        granaryBuilding = false;
        granaryBuilderSN = -1; // 释放建造者，让其参与任务分配
    }
    

}













// 建造谷仓
void UsrAI::buildGranary(const tagInfo& myInfo)
{
    // 谷仓建造者已在主函数中分配，这里只执行建造逻辑
    
    if (granaryBuilderSN != -1 && !granaryBuilding) {
        for (const auto& f : myInfo.farmers) {
            if (f.SN == granaryBuilderSN && f.NowState == HUMAN_STATE_IDLE) {
                auto buildPos = findSuitableBuildPosition(myInfo);
                if (buildPos.first != -1 && buildPos.second != -1) {
                    if (isAreaSuitableForBuilding(buildPos.first, buildPos.second, myInfo)) {
                        int result = HumanBuild(granaryBuilderSN, BUILDING_GRANARY, buildPos.first, buildPos.second);
                        if (result > 0) {
                            granaryBuilding = true;
                        }
                    }
                }
                break;
            }
        }
    }
    
    // 谷仓建造完成检查已移到 checkGranaryStatus 函数中
}

// 升级到工具时代
void UsrAI::upgradeToToolAge(const tagInfo& myInfo)
{
    // 找到市镇中心
    int centerSN = -1;
    for (const auto& building : myInfo.buildings) {
        if (building.Type == BUILDING_CENTER) {
            centerSN = building.SN;
            break;
        }
    }
    
    if (centerSN == -1) {
        return;
    }
    
    // 检查市镇中心是否正在升级
    bool isUpgrading = false;
    for (const auto& building : myInfo.buildings) {
        if (building.SN == centerSN && building.Project != 0) {
            isUpgrading = true;
            break;
        }
    }
    
    // 如果没有在升级，开始升级时代
    if (!isUpgrading) {
        BuildingAction(centerSN, BUILDING_CENTER_UPGRADE);
    }
}

// 检查建造者是否能到达目标位置
bool UsrAI::canBuilderReachPosition(int builderSN, int targetX, int targetY, const tagInfo& myInfo)
{
    // 找到建造者
    const tagFarmer* builder = nullptr;
    for (const auto& farmer : myInfo.farmers) {
        if (farmer.SN == builderSN) {
            builder = &farmer;
            break;
        }
    }
    
    if (!builder) {
        return false;
    }
    
    // 计算曼哈顿距离
    int distance = abs(builder->BlockDR - targetX) + abs(builder->BlockUR - targetY);
    
    // 如果距离太远，认为无法到达
    if (distance > 30) {
        return false;
    }
    
    // 简化检查：只检查建造者到目标位置的基本可达性
    // 不再进行复杂的路径阻挡检查，因为游戏引擎会处理路径规划
    
    // 检查目标位置本身是否被占用（这已经在isAreaSuitableForBuilding中检查过了）
    // 这里只做基本的距离和状态检查
    
    // 如果建造者距离目标位置合理，认为可以到达
    return true;
}

// 如果建造者站在将要建造的2x2范围内，则将其移动到相邻的可站立平地草地上
bool UsrAI::relocateBuilderOutOfFootprint(int builderSN, int buildX, int buildY, const tagInfo& myInfo)
{
    // 定位建造者
    const tagFarmer* builder = nullptr;
    for (const auto& farmer : myInfo.farmers) {
        if (farmer.SN == builderSN) { builder = &farmer; break; }
    }
    if (!builder) return false;

    // 判断是否在2x2脚印内
    if (builder->BlockDR >= buildX && builder->BlockDR < buildX + 2 &&
        builder->BlockUR >= buildY && builder->BlockUR < buildY + 2) {
        // 在脚印内：寻找周围一圈可站立的平地草地空位
        for (int dx = -1; dx <= 2; ++dx) {
            for (int dy = -1; dy <= 2; ++dy) {
                int nx = buildX + dx;
                int ny = buildY + dy;
                // 跳过脚印内部
                if (dx >= 0 && dx < 2 && dy >= 0 && dy < 2) continue;
                if (nx < 0 || ny < 0 || nx >= MAP_L || ny >= MAP_U) continue;
                if (isSingleTileFreeFlatGrass(nx, ny, myInfo)) {
                    double moveDR = nx * BLOCKSIDELENGTH + BLOCKSIDELENGTH / 2.0;
                    double moveUR = ny * BLOCKSIDELENGTH + BLOCKSIDELENGTH / 2.0;
                    HumanMove(builderSN, moveDR, moveUR);
                    return true;
                }
            }
        }
        // 若周围未找到合适落点，允许稍远一些（半径2）
        for (int dx = -2; dx <= 3; ++dx) {
            for (int dy = -2; dy <= 3; ++dy) {
                int nx = buildX + dx;
                int ny = buildY + dy;
                if (nx < 0 || ny < 0 || nx >= MAP_L || ny >= MAP_U) continue;
                if (isSingleTileFreeFlatGrass(nx, ny, myInfo)) {
                    double moveDR = nx * BLOCKSIDELENGTH + BLOCKSIDELENGTH / 2.0;
                    double moveUR = ny * BLOCKSIDELENGTH + BLOCKSIDELENGTH / 2.0;
                    HumanMove(builderSN, moveDR, moveUR);
                    return true;
                }
            }
        }
        return false;
    }
    // 本不在脚印内，无需移动
    return true;
}

// 单格可站立校验：平地+草地，且无建筑/资源/单位占用
bool UsrAI::isSingleTileFreeFlatGrass(int x, int y, const tagInfo& myInfo)
{
    if (x < 0 || y < 0 || x >= MAP_L || y >= MAP_U) return false;
    if (myInfo.theMap == nullptr) return false;
    int height = (*myInfo.theMap)[x][y].height;
    int pattern = (*myInfo.theMap)[x][y].type;
    if (height != MAPHEIGHT_FLAT || pattern != MAPPATTERN_GRASS) return false;
    for (const auto& b : myInfo.buildings) if (b.BlockDR == x && b.BlockUR == y) return false;
    for (const auto& r : myInfo.resources) if (r.BlockDR == x && r.BlockUR == y) return false;
    for (const auto& f : myInfo.farmers) if (f.BlockDR == x && f.BlockUR == y) return false;
    for (const auto& a : myInfo.armies) if (a.BlockDR == x && a.BlockUR == y) return false;
    for (const auto& f : myInfo.enemy_farmers) if (f.BlockDR == x && f.BlockUR == y) return false;
    for (const auto& a : myInfo.enemy_armies) if (a.BlockDR == x && a.BlockUR == y) return false;
    return true;
}


